import { decode, encode } from "cbor-x";
import { deviceFetch, HEADER_PUSH_EC, type ErrInfo } from "./http"
import type { DeviceStatus } from "./models";
import { createUrl } from "@/utils/utils";


export default {
    async notify(cmd: string, body: Uint8Array<ArrayBuffer> | null = null) {
        await deviceFetch(`/remove/notify?cmd=${cmd}`, 'POST', body);
    },

    async notifyAck(cmd: string, body: Uint8Array<ArrayBuffer> | null = null) {
        await deviceFetch(`/remote/notify_ack?cmd=${cmd}`, 'POST', body);
    },

    async ping() {
        await deviceFetch('/remote/ping', 'GET');
    },

    async req(cmd: string, duration: number, body: Uint8Array<ArrayBuffer> | null = null) {
        const resp = await deviceFetch(`/remote/req?cmd=${cmd}&duration=${duration}`, 'POST', body);
        const ec = resp.header.get(HEADER_PUSH_EC);
        if (ec == null) {
            throw 'ec is none';
        }
        const ec2 = parseInt(ec);
        if (isNaN(ec2)) {
            throw 'ec is invalid';
        }
        if (ec2 != 0) {
            const info = decode(resp.body) as ErrInfo;
            throw `错误:${info.err_code} => ${info.err_msg}`; 
        }
        return resp.body;
    },

    async appVersion() {
        const res = await this.req('/app_version', 3);
        return decode(res) as string;
    },

    async vendFlag() {
        const res = await this.req('/get/vend', 3);
        return decode(res) as boolean;
    },

    async vendRefresh() {
        await this.req('/vend/refresh', 3);
    },

    async uploadOrder() {
        await this.req('/upload_order', 15);
    },

    async reset() {
        await this.notifyAck('/reset');
    },

    async updateMcu(firmId: number) {
        await this.req('/mcu_update', 30 * 1000, encode({ firmId }));
    },

    async updateApp(firmId: number) {
        await this.notifyAck('/app_update', encode({ firmId }));
    },

    async deviceStatus() {
        const res = await this.req('/status/device', 3000);
        return decode(res) as DeviceStatus;
    },
    
    async screenShot() {
        const res = await this.req('/screen_shot', 10 * 1000);
        return res;
    },

    async productInit() {
        const res = await this.req("/product/init", 10 * 1000);
        return res;
    }
}

